/**
 * <pre>
 * 紫光软件系统有限公司广电事业部
 * Copyright (C): 2011
 * 
 * 文件名称：
 * com.unis.iptv.client.ClientCustomContext.java
 * 
 * 文件描述: 
 * TODO 请求Client
 * 
 * Notes:
 * 修改历史(作者/日期/改动描述):
 * 杨飞宇/2011-8-8/初始化版本。
 * </pre>
 */
package com.unis.iptv.client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.unis.iptv.common.http.StreamTool;
import com.unis.iptv.common.utils.GlobalUtil;

/**
 * @date 2011-8-8
 * @author 杨飞宇
 */
public class ClientCustomContext {
	private static Log iptvCourse = LogFactory.getLog("iptvCourse");
	
	public static String getCustomContext(String url) throws Exception {
		iptvCourse.info(url);
		DefaultHttpClient httpClient = GlobalUtil.httpClient;
		HttpGet httpGet = new HttpGet(url);
		// if (GlobalUtil.isCap == 1)
		// httpGet.addHeader("Cookie", GlobalUtil.cookie);
		// if (GlobalUtil.isProxy == 1) {
		// HttpHost proxy = new HttpHost("10.130.128.223", 808, "http");
		// httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		// proxy);
		// }
		HttpResponse httpResponse = httpClient.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		String content = EntityUtils.toString(entity, "GBK");
		httpGet.abort();
		return content;
	}
	
	public static void executeRequest(String url) throws Exception {
		DefaultHttpClient httpClient = GlobalUtil.httpClient;
		HttpGet httpGet = new HttpGet(url);
		// if (GlobalUtil.isCap == 1)
		// httpGet.addHeader("Cookie", GlobalUtil.cookie);
		// if (GlobalUtil.isProxy == 1) {
		// HttpHost proxy = new HttpHost("10.130.128.223", 808, "http");
		// httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
		// proxy);
		// }
		HttpResponse httpResponse = httpClient.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		EntityUtils.toString(entity, "GBK");
		httpGet.abort();
	}
	
	/**
	 * post提交带参数 临时用
	 * 
	 * @author 杨飞宇 @2012-5-31
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String postCustomContext(String url) throws Exception {
		DefaultHttpClient httpClient = GlobalUtil.httpClient;
		HttpPost httpost = new HttpPost(
				"http://222.241.222.140:8080/iptvepg/function/frameset_builder.jsp");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		
		nvps.add(new BasicNameValuePair("BUILD_ACTION", "FRAMESET_BUILDER"));
		nvps.add(new BasicNameValuePair("MAIN_WIN_SRC",
				"http://222.241.222.140:8080/iptvepg/frame675/portal.jsp"));
		nvps.add(new BasicNameValuePair("NEED_UPDATE_STB", "1"));
		
		httpost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));
		
		HttpResponse response = httpClient.execute(httpost);
		HttpEntity entity = response.getEntity();
		String content = EntityUtils.toString(entity, "GBK");
		httpost.abort();
		return content;
	}
	
	public static String getRequest(String reqUrl) throws IOException {
		return getRequest(reqUrl, "GBK");
	}
	
	public static String getRequest(String reqUrl, String charsetName)
			throws IOException {
		byte[] bytes = sendGetRequest(reqUrl);
		return new String(bytes, charsetName);
	}
	
	/**
	 * 通过HttpURLConnection模拟get请求
	 * 
	 * @author 杨飞宇 @2013-1-4
	 * @param reqUrl
	 * @return
	 * @throws IOException
	 */
	public static byte[] sendGetRequest(String reqUrl) throws IOException {
		URL getUrl = new URL(reqUrl);
		HttpURLConnection connection = (HttpURLConnection) getUrl
				.openConnection();
		InputStream inStream = connection.getInputStream();
		return StreamTool.readInputStream(inStream);
	}
	
	public static String postRequestByForm(String reqUrl, String params)
			throws IOException {
		byte[] bytes = sendPostRequestByForm(reqUrl, params);
		return new String(bytes, "GBK");
	}
	
	public static String postRequestByForm(String reqUrl, String params,
			String charsetName) throws IOException {
		byte[] bytes = sendPostRequestByForm(reqUrl, params);
		return new String(bytes, charsetName);
	}
	
	/**
	 * 通过HttpURLConnection模拟post表单提交
	 * 
	 * @author 杨飞宇 @2013-1-4
	 * @param path
	 * @param params
	 *            name=lybeta&age=24
	 * @return
	 * @throws Exception
	 */
	public static byte[] sendPostRequestByForm(String reqUrl, String params)
			throws IOException {
		URL url = new URL(reqUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");// 提交模式
		conn.setConnectTimeout(10000);// 连接超时 单位毫秒
		conn.setReadTimeout(2000);// 读取超时 单位毫秒
		conn.setInstanceFollowRedirects(false);
		conn.setDoOutput(true);// 是否输入参数
		byte[] bypes = params.toString().getBytes();
		conn.getOutputStream().write(bypes);// 输入参数
		InputStream inStream = conn.getInputStream();
		return StreamTool.readInputStream(inStream);
	}
	
	public static String getNameValuePairsByContent(String response) {
		StringBuffer params = new StringBuffer();
		String regex = "\\s*(<input type=[\"']hidden[\"'] name=[\"'](\\S+)[\"'] value=[\"'](\\S+)[\"']\\s*>)+\\s*";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(response.replaceAll("\n", ""));
		while (m.find()) {
			params.append("&").append(m.group(2)).append("=")
					.append(m.group(3));
			response = response.replace(m.group(1), "");
			m = p.matcher(response);
		}
		return params.toString().substring(1);
	}
	
	public static String downloadPictureByUrl(String url) throws Exception {
		System.out.println("图片下载路径：" + url);
		DefaultHttpClient httpClient = GlobalUtil.httpClient;
		HttpGet httpGet = new HttpGet(url);
		HttpResponse httpResponse = httpClient.execute(httpGet);
		HttpEntity entity = httpResponse.getEntity();
		String savePath = GlobalUtil.picSavePath
				+ url.substring(url.lastIndexOf("/"));
		File storeFile = new File(savePath);
		FileOutputStream output = new FileOutputStream(storeFile);
		// 得到网络资源的字节数组,并写入文件
		output.write(EntityUtils.toByteArray(entity));
		output.close();
		httpGet.abort();
		return savePath.replace("/server/static_server/server/", "");
	}
	
	public static void main(String[] args) throws Exception {
		GlobalUtil.initConfiguration();
		String url = "..images/poster/20121116002730.jpg";
		System.out.println(url.substring(2));
		// System.out.println(url.substring(url.lastIndexOf("/")));
		downloadPictureByUrl("http://10.255.128.8:8080/iptvepg/images/poster/20121116002730.jpg");
	}
}
